package gui.parta;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 *
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
public class MultiDataPacket extends DataPacket {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(MultiDataPacket.stringToHex(new String[]{"ABC", "123A"})));
        System.out.println(MultiDataPacket.convertToHexDataPacket(new String[]{"ABC", "123A"}));
        // AA034142435085BB
        // AA04313233417BD7BB
        System.out.println(Arrays.toString(MultiDataPacket.getMultiDataFromHexDataPacket("AA04313233417BD7BB")));
    }

    // Part A.2-2-a
    public static String[] stringToHex(String[] str) {
        String[] results = new String[str.length];
        for (int i = 0; i < str.length; i++) {
            String result = convertToDataPacket(str[i]);
            results[i] = result;
        }
        return results;
    }

    // Part A.2-2-b
    public static String convertToHexDataPacket(String[] data) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            String s = stringToHex(data[i]);
            if (i < data.length - 1) {
                sb.append(s).append(",");
            } else {
                sb.append(s);
            }
        }
        return sb.toString();
    }

    // Part A.2-2-c
    public static String[] getMultiDataFromHexDataPacket(String hexData) {
        String[] res = new String[5];
        // 数据包 = 头，数据长度，数据段，CRC代码和尾巴
        String header = hexData.substring(0, 2);
        String len = hexData.substring(2, 4);
        String dataSeg = hexData.substring(4, hexData.length() - 6);
        String crc = hexData.substring(hexData.length() - 6).substring(0, 4);
        String tail = hexData.substring(hexData.length() - 2);
        // 异常判断
        String dataStr = getDataFromDataPacket(hexData);
        String vLen = dataStr.length() > 10 ? dataStr.length() + "" : "0" + dataStr.length();
        String vDataSeg = stringToHex(dataStr);
        String vCrc = CRC16.getCRC(dataStr.getBytes(StandardCharsets.UTF_8));
        if ("AA".equals(header) && vLen.equals(len) && vDataSeg.equals(dataSeg) && vCrc.equals(crc) && "BB".equals(tail)) {
            res[0] = header;
            res[1] = len;
            res[2] = dataSeg;
            res[3] = crc;
            res[4] = tail;
        } else {
            try {
                throw new DataPacketException(1, "数据包验证失败！");
            } catch (DataPacketException e) {
                e.printStackTrace();
            }
        }
        return res;
    }
}
